package com.cn.ycy.filter;


import com.cn.ycy.ResponseDecorator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * 全局 GlobalFilter
 */
//@Component
//@ComponentScan
public class YcyGateWayFilter implements GlobalFilter, Ordered {

  private Logger logger = LoggerFactory.getLogger(YcyGateWayFilter.class);

  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

    URI uri = exchange.getRequest().getURI();
    logger.info("filter uri" + uri);

//    String rawQuery = uri.getRawQuery();
//
//    //新增request参数
//    String query = "userId=111";
//
//    URI newUri = UriComponentsBuilder.fromUri(uri)
//            .replaceQuery(query.toString()).build(true).toUri();
//    logger.info("filter new uri" + newUri);

//    ServerHttpRequest request = exchange.getRequest().mutate().uri(newUri)
//            .build();

    //改写response ...
    ResponseDecorator decorator = new ResponseDecorator(exchange.getResponse());

//    return chain.filter(exchange.mutate().request(request).response(decorator).build());

    return chain.filter(exchange.mutate().response(decorator).build());

  }

  @Override
  public int getOrder() {
    return 0;
  }


}
